/*
 * @Description:
 * @Author: fhw
 * @Date: 2023-01-09 15:49:09
 */
import { ChatRecord, HistorySession, User } from '@/interface'
import { PropType } from 'vue'
import * as IndexedDB from '@/indexedDB'
import { equals, last, clone, isNil } from 'ramda'
/*
 * @Description:
 * @Author: fhw
 * @Date: 2023-01-09 15:49:09
 */
export const emitEvent = ['updateLatestNews', 'sendMessage']
export const props = {
	historySession: {
		type: Array as PropType<HistorySession[]>,
		default: [],
	},
	onSendMessage: {
		type: Function as PropType<(user: User) => void>,
	},
	sendMessageUserState: {
		type: Object as PropType<HistorySession>,
		default: {},
	},
} as const

export const $styles = {
	searchIconSize: '17px',
}
// 获取聊天记录并写入indexedDB数据库
export async function getChatCommunication(friend: HistorySession) {
	const userId = localStorage.getItem('userId') as string
	const historicalUserSessionsId = friend.historicalUserSessionsId
	const parmas: API.blog.chatRecord.getUserChatRecord.Params = {
		userId: Number(userId),
		to_userId: historicalUserSessionsId,
		pageSize: 20,
		group_id: undefined,
	}
	if (!isNil(friend.chatUserGroup)) {
		parmas.to_userId = undefined
		parmas.group_id = historicalUserSessionsId
	}
	const { success, data } = await API.blog.chatRecord.getUserChatRecord.request(parmas)
	if (success) {
		// 获取聊天记录并比对indexedDB数据库聊天记录是否最新数据
		const userChatRecordReadAll = (await IndexedDB.readAll(
			`user-chat-record-${historicalUserSessionsId}`
		)) as ChatRecord[]
		// bug
		if (!equals(last(userChatRecordReadAll)?.id, friend.latestNews?.id)) {
			IndexedDB.clearTable(`user-chat-record-${friend?.historicalUserSessionsId}`)
			data.data.forEach((chatRecord: ChatRecord) => {
				IndexedDB.add<ChatRecord>(`user-chat-record-${friend?.historicalUserSessionsId}`, clone(chatRecord))
			})
		}
	}
}
